package com.service;

import com.dao.GoodsDao;
import com.entity.Goods;
import com.entity.Tops;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

/*
* 商品服务
* */
@Service
public class GoodService {
    @Autowired
    private GoodsDao goodsDao;

    @Autowired
    private TopService topService;

    @Autowired
    private TypeService typeService;

    /**
     * 封装商品
     * @param list
     * @return
     */
    private List<Goods>packGood(List<Goods>list){
        for (Goods good:list){
            good=packGood(good);
        }
        return list;
    }

    public List<Goods> getListByType(int typeId, int page, int size){
        return typeId > 0 ? packGood(goodsDao.selectListByTypeId(typeId,
                size * (page-1),size)) : this.getList(page,size);
    }

    public int getCount(){
        return goodsDao.selectCount();
    }

    public long getCountByType(int typeId){
        return typeId > 0 ? goodsDao.selectCountByTypeId(typeId) : this.getCount();
    }

    public long getCountByTopType(byte type){
        return goodsDao.selectCountByTypeId(type);
    }

    private Goods packGood(Goods good){
        if (good != null){
            good.setType(typeService.get(good.getTypeId()));
            good.setTop(Objects.nonNull(topService.getByGoodIdAndType(good.getId(),
                    Tops.TYPE_TODAY)));
        }
        return good;
    }

    public List<Goods> getList(int page,int size){
        return packGood(goodsDao.selectList(size * (page-1),size));
    }

    public List<Goods> getListByTopType(byte type,int page,int size){
        return packGood(goodsDao.selectListByTopType(type,size * (page-1), size));
    }

    public List<Goods> getListOrderSales(int page,int size){
        return packGood(goodsDao.selectListOrderSales(size * (page-1), size));
    }

    public Goods get(int id){
        return packGood(goodsDao.select(id));
    }
}
